<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 18-5-28
 * Time: 下午5:50
 */

namespace database;

use config\Config;
class MyMongo
{

    private static $database;

    public function __construct()
    {
    }

    /*
    数据库操作例子:
    
    单条插库 MyMongo::insertDB('aaa', array('name'=>xxx, 'age'=>000));
    多条插库 MyMongo::insertDBMore('aaa', array(array('name'=>xxx, 'age'=>000), array('name'=>ccc, 'age'=>111)));
    查询 MyMongo::selectDB('aaa', array('age'=>11), array('name'=>1, 'age'=>1));
    修改 MyMongo::updateDB('aaa', array('name'=>'tvmining'), array('age'=>1));
    删除 MyMongo::deleteDB('aaa', array('age'=>101), 1);
    */

    public static function conn(){
        self::$database = C('mongo_db');
        $mongoConf = Config::config("mongo");
        try{
            if(empty($mongoConf["user"]) && empty($mongoConf["password"])){
                $uri = "mongodb://".$mongoConf["host"];
            }else{
                $uri = "mongodb://".$mongoConf["user"].":".$mongoConf["password"]."@".$mongoConf["host"];//."/".self::$database;
            }
            //use userName and password
            //$db = new \MongoDB\Driver\Manager("mongodb://user:passwod@".$mongoConf["host"]."/".self::$database);
            $db = new \MongoDB\Driver\Manager($uri);
        }catch (\Exception $e){
            $errRs = array(
                "errMsg" => "connect to mongoDb err",
                "msg"=>$e->getMessage(),
            );
            mLogs("error","mongo_connect",$errRs,"mongo");
        }
        return $db;
    }

    /* 插入数据(单条)
    *   [string]table:表名
    *   [array]document:插库数据[数组]
    *   return bool
    */
    public static function insertDB($table, $document)
    {
        if (!is_array($document) || empty($document)) return false;
        //$document = array('name'=>'tvm', 'age'=>10, 'url'=>array('www.tvmining.com', 'tvmining.cn'));
        $conn = self::conn();
        $bulk = new \MongoDB\Driver\BulkWrite;
        $_id= $bulk->insert($document);
        $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);

        try {
            $result = $conn->executeBulkWrite(self::$database . '.' . $table, $bulk, $writeConcern);
        }catch (\Exception $e){
            //echo $e->getMessage();exit;
            return false;
        }
        return true;
    }

    /* 插入数据(多条)
    *   [string]table:表名
    *   [array]documentArr:插库的多条数据集合[数组]
    *   return bool
    */
    public static function insertDBMore($table, $documentArr)
    {
        if (!is_array($documentArr) || empty($documentArr)) return false;
        $conn = self::conn();
        $bulk = new \MongoDB\Driver\BulkWrite;

        foreach ($documentArr as $key => $document) {
            $bulk->insert($document);
        }
        $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        try {
            $result = $conn->executeBulkWrite(self::$database . '.' . $table, $bulk, $writeConcern);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /* 查询
    *   [string]table:表名
    *   [array]where:查询条件[数组]
    *   [array]filter:需求 例:projection显示字段[数组] 默认全部显示,删选字段:0为隐藏1为只显示某字段
    *   return bool(失败) | array
    */
    public static function selectDB($table, $where, $filter=[])
    {
        if (!is_array($where) || empty($where)) return false;
        if (!empty($filter)) {
            if (!is_array($filter)) return false;
        }
        $conn = self::conn();
        $query = new \MongoDB\Driver\Query($where, $filter);
        $data = $conn->executeQuery(self::$database.'.'.$table, $query);
        if (!$data) return false;
        $res = array();
        foreach ($data as $k=>$v){
            $id = (string)$v->_id;
            $res[$k] = (array)$v;
            unset($res[$k]['_id']);
            $res[$k]['_id'] = $id;
        }
        return $res;
    }


    /* 修改
    *   [string]table:表名
    *   [array]where:修改条件[数组]
    *   [array]data:修改内容
    *   return bool
    */
    public static function updateDB($table, $where, $data, $option = array())
    {
        if (!is_array($where) || empty($where)) return false;
        if (!is_array($data) || empty($data)) return false;
        $conn = self::conn();
        $bulk = new \MongoDB\Driver\BulkWrite;
        $bulk->update($where, $data, $option);//第一个是条件；第二个参数是修改的内容；第三个没有找到条件的项是否添加，默认false；第四个参数是是否多个结果修改，默认false。

        $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        try {
            $result = $conn->executeBulkWrite(self::$database . '.' . $table, $bulk, $writeConcern);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /* 删除
    *   [string]table:表名
    *   [array]where:删除条件[数组]
    *   [int]limit:linit:1.删除第一条匹配数据 0.删除所有匹配数据
    *   return bool
    */
    public static function deleteDB($table, $where, $limit)
    {
        if (!is_array($where) || empty($where)) return false;
        if (!in_array($limit, array(1,0)) ) return false;
        $conn = self::conn();
        $bulk = new \MongoDB\Driver\BulkWrite;
        $bulk->delete($where, array('limit' => $limit));//linit:1.删除第一条匹配数据 0.删除所有匹配数据

        $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        try {
            $result = $conn->executeBulkWrite(self::$database . '.' . $table, $bulk, $writeConcern);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }


}